﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Krilib.Control.Dialogs
{
    public partial class ImageViewer : Form
    {
        public Uri imageUri { get; set; }
        public ImageViewer()
        {
            InitializeComponent();
        }

        private void ImageViewer_Shown(object sender, EventArgs e)
        {
            ShowImage(false);
        }

        private void ShowImage(bool refresh)
        {
            if (imageUri == null) return;
            if (Bridge.ImageManager.IsCacheExists(imageUri) && !refresh)
            {
                imageRenderer.Image = Bridge.ImageManager.GetImage(imageUri, refresh);
            }
            else
            {
                Bridge.ImageManager.GetImageCallback(imageUri, refresh, new Krilib.Bridges.GetImageCallbackDelegate(
                    (url, img) =>
                    {
                        imageRenderer.Image = img;
                    }
                    ));
                imageRenderer.Image = Properties.Resources.loading;
            }
        }

        private void reloadImage_Click(object sender, EventArgs e)
        {
            ShowImage(true);
        }

        private void imgSave_Click(object sender, EventArgs e)
        {
            if (imageRenderer.Image == null) return;
            var arg = imageUri.AbsolutePath.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
            if (arg.Length == 0) return;
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                sfd.FileName = arg[arg.Length - 1];
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    imageRenderer.Image.Save(sfd.FileName);
                }
            }
        }

        private void ImageViewer_Deactivate(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }
    }
}
